package com.posjiajia.user.operator.controller;

import com.posjiajia.user.core.bo.UserBo;
import com.posjiajia.user.core.vo.UserVo;
import com.posjiajia.user.operator.contant.UserOperatorContant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author zhenhua.sun
 * @title com.posjiajia.user.operator.controller
 * @date 8/28/16
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserBo userBo;
    /**
     * 登录展示
     * @return
     */
    @RequestMapping("tologin")
    public String loginUi(){
        return "login";
    }

    /**
     * 登录
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(String userName, String password, HttpServletRequest request){
//        String requestIp = getIpAddr(request);
        UserVo userVo;
        try {
            userVo = userBo.login(userName,password,null);
        }catch (Exception e){
            logger.error("user login error,userName:{}",userName);
            return "redirect:/login/tologin";
        }
        String referer = request.getHeader("Referer");
        if (!StringUtils.isEmpty(referer) && !referer.contains("tologin")){
            return "redirect:"+referer;
        }
        request.setAttribute("userVo",userVo);
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("userVo",userVo);
        httpSession.setAttribute(UserOperatorContant.ISLOGIN,"ok");
        return "redirect:/index";
    }

    /**
     * 获取ip地址
     * @param request
     * @return ip
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
